package Audio;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.sound.sampled.*;
import model.soundSetting;


/**
 * La classe AudioPlay gére la lecture Audio <br>
 * @author Romain Bustos
 * @author Matthieu Perrin
 * @version 1.0
 */
public class AudioPlay extends soundSetting{
    
    AudioFormat format;
    boolean pause = false;

    
    public AudioPlay(AudioFormat format) {
        this.format = format;
    }
    
    public void playAudio(byte audio[]) {

    try { 
      InputStream input = new ByteArrayInputStream(audio);
      final AudioInputStream ais = new AudioInputStream(input, format, audio.length / format.getFrameSize());
      DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
      final SourceDataLine line = (SourceDataLine)AudioSystem.getLine(info);
      line.open(format);
      line.start();

      Runnable runner = new Runnable() {
        int bufferSize = 640;
        byte Buffer[] = new byte[bufferSize];
 
        @Override
        public void run() {
          try {
            int count = -1;
            while ((count = ais.read(Buffer)) != -1) {
                
                if ( !pause )
                    line.write(Buffer, 0, Buffer.length);
                
                  
            }
            line.drain();
            line.close();
          } catch (IOException e) {
            System.err.println("I/O problems: " + e);
            //System.exit(-3);
          }
        }
      };
      Thread playThread = new Thread(runner);
      playThread.start();
    } catch (LineUnavailableException e) {
        System.err.println("Line unavailable: " + e);
        //System.exit(-4);
    } 
  }
    public void pause(){
        if(pause)
            this.pause = false;
        else
            this.pause = true;
    }

}
